package com.wenhai.concurrency.thread.pool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName ExecutorServiceMethodDemo
 * @Description {@link ExecutorService} 方法示例
 * @Author 谢文海
 * @Date 2021/4/27 0:39
 * @Version 1.0
 **/
public class ExecutorServiceMethodDemo {
    public static void main(String[] args) throws Exception {
        List<Callable<String>> list = new ArrayList<>();
        list.add(new MyCallableA());
        list.add(new MyCallableB());
        list.add(new MyCallableBInterrupted());
        ExecutorService executor = Executors.newCachedThreadPool();

        invokeAny(executor, list);
        invokeAll(executor, list);

    }


    private static void invokeAny(ExecutorService executor, List<Callable<String>> callables) throws Exception{
        String result = executor.invokeAny(callables);
        System.out.println("==========" + result);
        System.out.println("zzzzzzzzzz");
    }
    private static void invokeAll(ExecutorService executor, List<Callable<String>> callables) throws Exception{
        List<Future<String>> futures = executor.invokeAll(callables,1,TimeUnit.SECONDS);
        futures.forEach(f -> {
            try {
                System.out.println("========invokeAll result========");
                System.out.print(f.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });

    }
}
